<template>
  <div class="goodsTypeIndex">
    <el-card class="box-card">
      <!-- one------------------------------------------------------- -->
      <div slot="header" class="clearfix header">
        <span>商品类型</span>
        <el-button type="primary" round @click="createFn">创建</el-button>
      </div>
      <!-- -------------------------------------------------------------- -->

      <!-- two----------data 指的是表格的数据----------------------------->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="role_id" label="编号" width="180">
        </el-table-column>
        <!-- 第一栏 -->
        <el-table-column
          prop="role_name"
          label="角色名称"
          width="180"
        ></el-table-column>
        <!-- 第二栏 -->
        <el-table-column
          prop="role_describe"
          label="角色描述"
          width="180"
        ></el-table-column>
        <!-- 第三栏 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="fenFn(scope.row)"
              >分配权限</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="editFn(scope.row)"
            >
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="delFn(scope.row.role_id)"
            >
            </el-button>
          </template>
        </el-table-column>
        <!-- 第四栏：里面包含两个按钮 使用插槽的方法  <template slot-scope="scope"></template>-->
      </el-table>
      <!-- ----------------------------------------------------------------------------- -->

      <!-- three----编辑弹框------------------------------------------------------------ -->
      <el-dialog
        title="编辑商品类型"
        :visible.sync="isShowEditTk"
        width="30%"
        :before-close="handleClose"
      >
        <!-- form -->
        <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="类型名称" prop="role_name">
            <el-input
              type="text"
              v-model="ruleForm.role_name"
              autocomplete="off"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <!-- /form -->
        <span>这是一段信息</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isShowEditTk = false">取 消</el-button>
          <el-button type="primary" @click="sumbit">确 定</el-button>
        </span>
      </el-dialog>
      <!-- --------------------------------------------------------------------------------------- -->

      <!-- 分配角色权限弹框 -->
      <el-dialog title="提示" :visible.sync="dialogVisible2" width="30%">
        <el-tree
          :data="data"
          show-checkbox
          node-key="auth_id"
          :default-expanded-keys="defaultCheck"
          :default-checked-keys="defaultCheck"
          :props="defaultProps"
          ref="tree2"
        >
          <!-- defaultCheck默认选中   node-key绑定权限角色id -->
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="quanFn">确 定</el-button>
        </span>
      </el-dialog>

      <!--  -->

      <!-- four分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage4"
        :page-sizes="[5, 20, 30, 40]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagetotal"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import {
  getJueseIndex,
  deleteJueseIndex,
  postJueseIndex,
  getQuanApi,
  putJueseIndex
} from "@/api";
export default {
  mounted() {
    this.initData();
  },
  methods: {
    //封装接口数据渲染页面
    initData() {
      getJueseIndex().then(res => {
        console.log(res);
        if (res.meta.state == 200) {
          this.tableData = res.data;
          this.pagetotal = parseInt(res.data.total);
        } else {
          this.$message.error(res.meta.msg);
        }
      });
    },

    //编辑
    editFn(rrow) {
      //显示默认数据显示
      this.ruleForm = rrow;
      //显示编辑弹框
      this.isShowEditTk = true;
    },
    sumbit() {
      this.isShowEditTk = false;
      postJueseIndex({
        role_name: this.ruleForm.role_name,
        role_describe: this.ruleForm.role_describe
      }).then(res => {
        // console.log(res);
        if (res.meta.state == 201) {
          this.initData();
          this.$message.success("成功");
        } else {
          this.$message.error(res.meta.msg);
        }
      });
    },

    //编辑分配权限弹框
    fenFn(rrow) {
      this.dialogVisible2 = true;
      //保存用户编号
      this.role_id = rrow.role_id;
      //请求接口获取权限菜单
      getQuanApi().then(res => {
        console.log(res);
        this.data = res.data;
        //这是请求接口后对默认值的判断
        this.defaultCheck = rrow.auth_ids_son
          ? rrow.auth_ids_son.split(",")
          : [];
      });
    },
    //点击权限弹框的确定按钮触发事件
    quanFn() {
      this.dialogVisible2 = false;
      //先对接口需要的数据进行判断处理
      //接口所需参数:
      //role_id角色编号  auth_ids所有勾选的权限编号（必须有父有子，中间用逗号隔开） auth_ids_son所有勾选的权限编号（只能子）
      //为了减少dom的查找，给html加ref vue会把带有ref的标签内存里面单独放一份 然后复制给this.$ref对象
      //通过this.$refs.键来获取
      // console.log(this.$refs.tree2.getCheckedNodes())
      //打印出来你会发现 如果你勾选了一级，打印出来的会有children 即有二级
      //                如果只勾选了二级，打印出来的只会有那个数据，没有children
      let allsonids = [];
      let allfatherandsonids = [];
      let all = this.$refs.tree2.getCheckedNodes();
      all.forEach(one => {
        //收集所有子，只要你没有children，那就是只有子,那就只传一个auth_id去确定身份
        if (!one.children) {
          allsonids.push(one.auth_id);
        }

        //收集既有父又有子，
        allfatherandsonids.push(one.auth_id);
        //只要有children的，auth_pid就是0，此时就不需要加auth_pid
        if (!one.children) allfatherandsonids.push(one.auth_pid);
      });
      let temp1 = [...new Set(allsonids)];
      let temp2 = [...new Set(allfatherandsonids)];

      console.log(temp1);
      console.log(temp2);

      //点击确定按钮，收集到有哪些权限被点击需要的，此时将其当参数去请求接口
      putJueseIndex({
        role_id: this.role_id,
        auth_ids: temp2.toString(),
        auth_ids_son: temp1.toString()
      }).then(res => {
        // console.log(res);
        if (res.meta.state == 200) {
          this.$message.success("成功");
        } else {
          this.$message.error(res.meta.msg);
        }
      });
    },

    //删除
    delFn(iid) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteJueseIndex({
            role_id: iid
          }).then(res => {
            // console.log(res);
            if (res.meta.state == 200) {
              this.initData();
              this.$message.success("成功");
            } else {
              this.$message.error(res.meta, msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //关闭
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },

    //返回
    createFn() {
      this.$router.push({ path: "/roles/create" });
    },
    //分页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pagesize = val;
      this.initData();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      //1.修改当前页
      this.pagenum = val;
      //2.重新请求数据
      this.initData(); //不同页面对应的数据不一样
    }
  },
  data() {
    return {
      //列表接口参数
      pagenum: 1,
      pagesize: 2,
      pagetotal: 0,

      //控制弹框是否显示
      isShowEditTk: false,
      //控制分配角色弹框是否显示
      dialogVisible2: false,
      //表单编辑数据
      ruleForm: {},
      rules: {
        //键 ruleForm里面的键
        //值 数组里面是一个个对象 赋值
        type_name: [
          { required: true, message: "请输入类型名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ]
      },
      //默认选中
      defaultCheck: [],
      //存放用户编号的变量(即当被点击分配权限按钮的时候，获取到当前行的所有数据，此时将当前行的用户编号存到一个变量里，方便在方法中直接使用)
      role_id: 0,
      //存放权限角色的变量
      data: [],
      defaultProps: {
        children: "children", //声明后端给的数据 子级是哪个字段
        label: "auth_name" //声明分类数，显示的名称，用哪个字段填充  //本次children的名称是ayth_name字段，这些都是接口数据内可以看到的
      },
      currentPage1: 5,
      currentPage2: 5,
      currentPage3: 5,
      currentPage4: 4,
      tableData: []
    };
  }
};
</script>
<style lang="scss" scoped>
.goodsTypeIndex {
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .el-pagination {
    margin-top: 20px;
    text-align: center;
  }
}
</style>
